package com.fzfnn.scrapbook.service.impl;

import com.fzfnn.scrapbook.mapper.PicturesMapper;
import com.fzfnn.scrapbook.service.PicturesService;
import com.fzfnn.scrapbook.util.ImageCompressUtil;
import com.fzfnn.scrapbook.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class PicturesServiceImpl implements PicturesService {

    @Autowired
    private PicturesMapper picturesMapper;
    @Autowired
    private RedisTemplate<String, String> redisMail;

    @Override
    public R avatar(MultipartFile file, String token, HttpServletRequest request) throws IOException {
        String userId = redisMail.opsForValue().get("token:" + token);
        if (userId == null) {
            return R.errorMsg("用户未登录或 token 无效");
        }
        if (file == null || file.isEmpty()) {
            return R.errorMsg("上传文件为空");
        }

        String fileName = UUID.randomUUID().toString() + ".webp";
        String projectRootPath = System.getProperty("user.dir");
        File uploadDir = new File(projectRootPath + "/static/img/avatar/");
        if (!uploadDir.exists()) uploadDir.mkdirs();

        File destFile = new File(uploadDir, fileName);
        // 始终固定大小压缩（头像），质量控制在 0.8
        ImageCompressUtil.compressFixedSize(file.getInputStream(), destFile, 0.8f, 128, 128, "webp");

        String imgUrl = "http://" + request.getServerName() + ":3000/static/avatar/" + fileName;
        picturesMapper.updateimgurl(imgUrl, Long.parseLong(userId));
        return R.success("上传成功", imgUrl);
    }

    @Override
    public R scrappictures(List<MultipartFile> files, String token, HttpServletRequest request) throws IOException {
        String userId = redisMail.opsForValue().get("token:" + token);
        if (userId == null) {
            return R.errorMsg("用户未登录或 token 无效");
        }

        List<String> imgUrls = new ArrayList<>();
        String projectRootPath = System.getProperty("user.dir");
        File uploadDir = new File(projectRootPath + "/static/img/scrapbook/");
        if (!uploadDir.exists()) uploadDir.mkdirs();

        for (MultipartFile file : files) {
            String fileName = UUID.randomUUID() + ".webp";
            File destFile = new File(uploadDir, fileName);

            // 新统一逻辑：能压就压，不能就只转 webp
            ImageCompressUtil.autoCompressToWebp(file.getInputStream(), destFile, file.getSize(), 0.9f, 1200);

            String imgUrl = "http://" + request.getServerName() + ":3000/static/scrapbook/" + fileName;
            imgUrls.add(imgUrl);
        }

        String imgUrlsString = String.join(",", imgUrls);
        redisMail.opsForValue().set("user:" + userId + ":imageUrls", imgUrlsString, 10, TimeUnit.MINUTES);

        return R.success("上传成功", imgUrlsString);
    }
}